package com.attendance.controller;

import com.attendance.Utils.Converter.VacationConverter;
import com.attendance.Utils.PaginationUtil;
import com.attendance.model.Biz.BizVacation;
import com.attendance.model.Form.VacationForm;
import com.attendance.model.Result.Response;
import com.attendance.model.Result.ResultCode;
import com.attendance.model.Vacation;
import com.attendance.service.IVacationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by inuyasha on 2016/11/29.
 */

@RestController
@RequestMapping("/vacation")
public class VacationController {

    @Autowired
    private IVacationService vacationService;

    @RequestMapping(value = "",method = RequestMethod.GET)
    public Response getAll(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows,
                           @RequestParam(defaultValue = "id") String sort, @RequestParam(defaultValue = "asc") String order,
                           @ModelAttribute VacationForm vacationForm){
        PaginationUtil.preset(page, rows, sort, order);
        Response response = new Response();
        List<BizVacation> list = vacationService.getAll(vacationForm);
        response.putResult(list);
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    public Response add(@ModelAttribute VacationForm vacationForm){
        Response response = new Response();
        try {
            Vacation vacation = VacationConverter.convert(vacationForm);
            vacationService.insertSelective(vacation);
        } catch (Exception e) {
            return new Response(ResultCode.VACATION_ADD_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.DELETE)
    public Response delete(@ModelAttribute VacationForm vacationForm){
        Response response = new Response();
        try {
            Vacation vacation = VacationConverter.convert(vacationForm);
            vacationService.deleteById(vacation.getId());
        } catch (Exception e) {
            return new Response(ResultCode.VACATION_DELETE_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "",method = RequestMethod.PUT)
    public Response update(@ModelAttribute VacationForm vacationForm){
        Response response = new Response();
        try {
            Vacation vacation = VacationConverter.convert(vacationForm);
            vacationService.updateSelectiveById(vacation);
        } catch (Exception e) {
            return new Response(ResultCode.VACATION_UPDATE_ERROR);
        }
        return response;
    }
}
